<template>
  <div class="layer_video_main">
    <div class="operator-area">
      <div class="left" v-if="true">
        <el-select
          v-model="sourceType"
          placeholder="请选择"
          @change="handleChange"
        >
          <el-option
            v-for="item in sourceOptions"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
            :disabled="item.disabled"
          />
        </el-select>
      </div>
      <div class="right">
        <el-button
          type="primary"
          class="add-button"
          icon="el-icon-plus"
          @click="handleAdd"
          >添加</el-button
        >
      </div>
    </div>
    <div class="table-area-wrap" v-if="true">
      <el-table
        border
        stripe
        ref="el"
        :height="height"
        :data="sourceInfo"
        class="table-area"
        :row-key="(row) => row.id"
        :reserve-selection="true"
        @select="handleSelectRow"
        :class="{ 'multiple-table': info['multiple'] }"
        @selection-change="handleSelectionChange"
      >
        <!--        @selection-change="handleSelectionChange"-->
        <el-table-column
          type="selection"
          :reserve-selection="true"
          v-if="checked"
        />
        <el-table-column prop="name" label="素材名称">
          <template v-slot="scope">
            <div class="name-inside" slot="reference">
              {{ scope.row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="素材类型">
          <template v-slot="scope">
            <div>{{ scope.row.type }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间">
          <template v-slot="scope">
            <div class="time" v-if="checked">{{ scope.row.createTime }}</div>
            <div @click="handleAdd(scope.row)" v-if="!checked">添加</div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { v4 as uuid } from "uuid";
import { ModelDesignApi } from "@/api/modeldesign";
import {
  concurrencyRequest,
  getImageExtension,
  getImageName,
} from "@/utils/common";
import * as types from "@c/public/form-designer/devType/datas-types";

export default {
  name: "ResourceInfo",

  props: {
    info: {
      type: Object,
      default: () => {
        return Object();
      },
    },
    multiple: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    checked: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
  },

  components: {},

  data() {
    return {
      sourceInfo: Array(),
      checkedInfo: Array(),
      selectedRow: "",
      sourceType: "",
      height: 350,
      sourceOptions: types["sourceOption"],
      queryParams: {
        name: "",
        classification: "",
        pageNum: 1,
        deptIds: Array(),
        pageSize: 9999,
      },
    };
  },

  computed: {},

  methods: {
    // 关闭
    handleClose() {
      this.$emit("handleCancel", false);
    },

    // 确认
    handleSure() {
      if (!!this.selectedRow) {
        this.handleClose();
        this.$emit("handleSure", this.selectedRow);
      } else {
        this.$message({
          type: "warning",
          message: "请先选择图片",
        });
      }
    },

    // 单选操作
    handleSelectRow(selection, val) {
      if (this.info && this.info.multiple) {
        this.selectedRow = [...selection];
      } else {
        // 接收两个参数，selection为所有选中数据的集合，val为当前选择的数据
        // 先将所有选中的数据变为未选中状态
        this.$refs.el.clearSelection();
        // 如果选择完当前数据后selection为空数组，说明现在是取消勾选，无选中数据
        if (selection.length === 0) {
          this.selectedRow = null; // 清空data中绑定的selectedRow
          return false;
        }
        // 切换最近一次选择数据的状态
        this.$refs.el.toggleRowSelection(val, true);
        // 更新data中的selectedRow
        this.selectedRow = val.url;
      }
    },

    // 全选操作
    handleSelectionChange(val) {
      if (!!val && !!val.length) {
        this.selectedRow = [...val];
      } else {
        this.selectedRow = Array();
      }
    },

    //   添加
    handleAdd() {
      const self = this;
      let result = Array();
      if (self.sourceType === "office") {
        concurrencyRequest(
          self.selectedRow,
          20,
          ModelDesignApi.getSourceChangePicture
        ).then((resp) => {
          let filterResult = Array();
          resp.forEach((item) => {
            if (item?.code === 200) {
              let data = item.data;
              filterResult.push(data);
            }
          });

          // 数组合并并去空
          let clearResult = self.$lodash.compact(
            self.$lodash.flatten(filterResult)
          );
          clearResult.forEach((item) => {
            let params = Object();
            Reflect.set(params, "id", uuid());
            Reflect.set(params, "name", getImageName(item));
            Reflect.set(params, "type", getImageExtension(item));
            Reflect.set(params, "classification", "image");
            Reflect.set(params, "url", item);
            Reflect.set(params, "size", 0);
            result.push(params);
          });
          if (result?.length) {
            self.$emit("backContent", result);
          }
        });
      } else {
        self.$emit("backContent", this.selectedRow);
      }
      // self.$refs["el"].clearSelection();
    },

    // 筛选资源类型
    handleChange(val) {
      this.sourceType = val;
      this.getSourceList();
    },

    // 选择对应元素
    handleRow(row) {
      const self = this;
      let tempMap = new Map();
      row.forEach((item) => {
        tempMap.set(item.id, item);
      });
      self.sourceInfo.forEach((item) => {
        const result = self.checkedInfo.findIndex((row) => row.id === item.id);
        if (tempMap.get(item.id)) {
          if (result < 0) {
            self.checkedInfo.push(item);
          }
        } else {
          if (result >= 0) {
            self.checkedInfo.splice(result, 1);
          }
        }
      });
      self.$emit("backContent", self.checkedInfo);
    },

    // 回显选中的数据
    handleToggleSelection(rows, el) {
      const self = this;
      if (rows?.length) {
        rows.forEach((item) => {
          // 切换选中状态
          self.$refs[el].toggleRowSelection(item, true);
        });
      } else {
        // 清空选中
        this.$refs[el].clearSelection();
      }
    },

    //获取资源
    async getSourceList() {
      const self = this;
      try {
        const resp = await ModelDesignApi.getAllMaterial(this.queryParams);
        if (resp && resp.code === 200) {
          this.sourceInfo = resp.data;
          self.$nextTick(() => {
            let rows = self.info?.content || Array();
            let rowId = self.$lodash.map(rows, "id");
            let checkedInfo = self.$lodash.filter(
              resp?.data || Array(),
              function (items) {
                return rowId.includes(items.id);
              }
            );
            self.handleToggleSelection(checkedInfo, "el");
          });
        }
      } catch (e) {
        let { data } = e.response;
        console.log(data);
      }
    },

    handleCancelChecked(row) {
      const self = this;
      const index = self.sourceInfo.findIndex((item) => item.id === row.id);
      if (index >= 0) {
        this.$refs["el"].toggleRowSelection(self.sourceInfo[index], false);
      }
    },
  },

  watch: {
    // 获取视频所有资源--如果是图片资源可能涉及文档
    info: {
      handler: async function (val) {
        let { type, content } = val;
        if (!this.$lodash.isEmpty(val)) {
          let arrType = Array();
          if (!!type) {
            arrType = type.split(",");
          }
          if (arrType?.length) {
            this.sourceType = arrType[0];
          } else {
            this.sourceType = type;
          }
          Reflect.set(this.queryParams, "classification", this.sourceType);
          await this.getSourceList();
          this.sourceOptions.forEach((item) => {
            Reflect.set(
              item,
              "disabled",
              !this.$lodash.includes(val.type, item.dictValue)
            );
          });
          this.checkedInfo = [...content];
        }
      },
      deep: true,
      immediate: true,
    },
  },
};
</script>


<style lang="scss">
.layer_video_main {
  :deep(.table-area th.el-table__cell .el-checkbox) {
    display: none !important;
  }

  :deep(.multiple-table th.el-table__cell .el-checkbox) {
    display: block !important;
  }
}
</style>

<style lang="scss" scoped>
@import "@/components/assets/style/layer";
@import "./assets/style";
</style>